/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
    useTheme,
    LayerLoading,
    Text,
    Button,
    IconTruck,
    IconArrowRight,
    Navbar,
    Toolbar,
    IconButton,
    IconArrowLeft,
    MenuList,
    MenuItem,
    IconMoreVertical,
    IconRefButton,
    List,
    ListItem,
    Skeleton,
    InputPure,
    IconX,
    Dialog,
    InputLine,
    Select,
    InputDatalist,
    ComboBoxDatalist,
    Spinner,
    CommitInput,
    ButtonRefComp,
    SuffixInput,
    InputGroup,
    TextArea,
    IconPrinter,
    LineColumn,
    Container,
    CheckSwitch,
    VerticalMenu,
    DdMenuItem,
    TwoHalfRightPanel
} from "customize-easy-ui-component";
//import {  useLookReportOfIsp } from "./db";

//import { Link as RouterLink, useLocation } from "wouter";
//import { TransparentInput } from "../../comp/base";
import { Link as RouterLink } from "../../routing/Link";
import {PreloadedQuery, usePreloadedQuery} from "react-relay/hooks";
import {TaskFeeSummQuery} from "./__generated__/TaskFeeSummQuery.graphql";
//import {noop} from "use-media/lib/utilities";

import {DivisionChooseQuery$data} from "../../unit/division/__generated__/DivisionChooseQuery.graphql";
import {getFeeTitleBe} from "../../dict/feeTitleBe";
import {asFeeTitleFeOb as FeeC, ContainerDesignClsTil, getFeeTitleFe} from "../../dict/feeTitleFe";
import {css} from "@emotion/react";

import {Dispatch, MutableRefObject, SetStateAction, useEffect} from "react";

import {
    Disposable,
} from 'relay-runtime';
//import useUpdateDetailMutation from "./useUpdateDetailMutation";
import {安全状况等级} from "../../device/edit/容器";
import {管道敷设式} from "../../pipeline/edit/管道单元";
import {InternalItemHandResult} from "../../report/comp/base";
import {InternalEditorResult} from "../../common/base";
import {ContainLine, TransparentInput} from "../../comp/base";
import useConfirmTaskFeeMutation from "./useConfirmTaskFeeMutation";
//import useReckonIspFeeMutation from "./useReckonIspFeeMutation";
//[HOOK限制]按钮点击函数内部直接上toast()或toaster.notify()很可能无法正常显示。而放在函数组件顶层render代码前却能正常。
const graphql = require("babel-plugin-relay/macro");

interface TaskFeeSummProps {
    id?: string;
    prepared: {
        //【特别注意】query路由器若不是提供这个类型的查询DetailConfigQuery，本组件也不会抛出异常！在usePreloadedQuery<DetailConfigQuery>()不报错！
        query: PreloadedQuery<TaskFeeSummQuery>;
    }
    children: React.ReactNode;
    routeData: any;
}
/**业务信息配置*/
export default function TaskFeeSumm(props: TaskFeeSummProps) {
    const theme = useTheme();
    const data = usePreloadedQuery<TaskFeeSummQuery>(
        graphql`
            query TaskFeeSummQuery($taskId: ID!) {
                node(id: $taskId)
                {
                    ... on Task {
                        id  feeOk dreason disfee charge
                    }
                }
            }
        `,
        props.prepared.query,
    );
    const { node:item, }=data;    //有多个分项报告[SimpleReport]
  //  const {call:updateDetailFunc,doing,called, result}= useUpdateDetailMutation();
    const {call:confirmTaskFeeFunc,doing:confing,called:confed, result:confrs}= useConfirmTaskFeeMutation();

    const commitBlurRef =React.useRef<HTMLDivElement | null>(null);
    //先试一试：直接在父辈同一个组件内直接做 编辑器方式的保存。 PreloadedQuery+Mutation()都在同一组件干。
    const [charge, setCharge] = React.useState<number|undefined>(Number(item!.charge) ||  Number(item!.disfee) || undefined);

    const [memo, setMemo] = React.useState<string|null>();
    //会根据参数判定输出类型啊！报错了,useRef<T>(initialValue: T|null): RefObject<T>; useRef<T>(initialValue: T): MutableRefObject<T>;
    const editorRef=React.useRef({} as InternalEditorResult);

    console.log("收费主页来taskSja:", props.routeData.params.taskId!,";isp=", props.routeData.params, "editorRef=",editorRef.current);

    if(!item) return(
        <Text  variant="h4"　css={{ textAlign: 'center' }}>
            没找到检验detId {props.routeData.params.ispId}。
        </Text>);
  return (
      <TwoHalfRightPanel
          title={ `关联的收费信息` }
          back={
              <RouterLink href={`/task/${props.routeData.params.taskId!}`}>
                  <IconButton  noBind  icon={<IconArrowLeft />}
                               variant="ghost"
                               label="后退"
                               size="md"
                               css={{
                                   marginRight: theme.spaces.sm,
                                   [theme.mediaQueries.md]: {
                                       display: "none"
                                   }
                               }}
                  />
              </RouterLink>
          }
          menu={
              <VerticalMenu>
                  <DdMenuItem label="功能待续"
                              onClick={(e) => {
                              }}/>
              </VerticalMenu>
          }
      >
            <Container>
                <div css={{
                    paddingBottom: theme.spaces.lg
                }}>
                    <Text variant="h5">任务级别汇总收费</Text>
                    <ContainLine display='应收费任务金额'>
                        <TransparentInput readOnly={true} value={item?.disfee || '请先去汇总'}/>
                    </ContainLine>
                    { item?.dreason &&
                        <Text>自动折扣说明：{item?.dreason || ''}</Text>
                    }
                    { charge?
                        <InputLine label={`实际收费金额:`}>
                            <SuffixInput  onSave={txt=> setCharge( Number(txt) || undefined)}
                                          type="number"  value={ charge || ''}>元</SuffixInput>
                        </InputLine> :
                        <Text variant="h5" css={{color: 'red' }} >请首先任务金额汇总</Text>
                    }
                    <InputLine label={`给审批人的理由:`}>
                        <CommitInput  value={ memo || ''}  onSave={txt => setMemo( txt || undefined) }
                               placeholder="如果实际收费金额比应收费任务金额少的，必须给出说明"
                        />
                    </InputLine>
                </div>
            </Container>
          {charge &&
              <ButtonRefComp
                  intent="primary"
                  disabled={item!.feeOk &&  charge===Number(item!.charge) }
                  ref={commitBlurRef}
                  css={{marginLeft: theme.spaces.sm}}
                  onPointerOver={(e: any) => {
                      commitBlurRef!.current!.focus();
                  }}
                  onPress={async () => {
                      //获取最新的儿孙组件编辑器数据
                      //const sendInp = editorRef.current!.doConfirm();
                      const sendInp={ amount: charge , memo };
                      await confirmTaskFeeFunc(props.routeData.params.taskId,sendInp as any);
                  }}
              >
                  确认采用这个实际收费
              </ButtonRefComp>
          }
          { confrs.warn && (
                  <Text  variant="h5"　css={{ textAlign: 'center' }}>
                      后端应答：{confrs.warn}，请处理后再来。
                  </Text>
          ) }
        <RouterLink href={"/tasks"}>
            查全部任务
        </RouterLink>

      </TwoHalfRightPanel>
  );
};


